package com.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.app.G;
import lib.common.R;




public class Utils {

	public final static String TAG = Utils.class.getSimpleName();

	
	/**
	 * 判断手机格式是否正确
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	/**
	 * 判断email格式是否正确
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 判断是否全是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 判断字符串是否是中文
	 * 
	 * @Title: isChineseChar
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param str
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	public static boolean isChineseChar(String str) {
		boolean temp = false;
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			temp = true;
		}
		return temp;
	}

	public static void saveNetData(Activity activity, String key, String value) {
		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(key, value);
		editor.commit();

	}

	public static String getNetData(Activity activity, String key) {
		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		return settings.getString(key, "");
	}

	/**
	 * 保存用户账号
	 * 
	 * @param activity
	 * @param userName
	 *            用户账号
	 * @param password
	 *            用户密码
	 */

	public static void saveUserInfo(Context activity, String userName,
			String password, boolean isRemember // , boolean auto_login
	) {
		boolean auto_login = true;

		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("isRemember", isRemember);
		editor.putBoolean("auto_login", auto_login);
		if (isRemember) {
			editor.putString("userName", userName);
			editor.putString("password", password);
		} else {
			editor.putString("userName", "");
			editor.putString("password", "");
		}
		editor.commit();
	}

	public static void clearUserPassword(Context activity) {

		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		SharedPreferences.Editor editor = settings.edit();
		{
			editor.putString("password", "");
		}
		editor.commit();
	}

	public static boolean canAutoLogin(Context activity) {
		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);

		boolean b = settings.getBoolean("auto_login", false);
		return b;
	}

	public static String getUserInfo(Context activity) {
		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				Context.MODE_PRIVATE);
		String re = "";

		{
			re += settings.getString("userName", "");
			re += "~";
			re += settings.getString("password", "");
		}

		return re;

	}

	// 设置
	public static boolean updateTimeAndCount(Activity activity, int value) {

		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		// if( settings.getString( "modify_time", "").length() == 0 ){
		// return true;
		// }
		// else
		{
			//
			boolean bResult = false;
			String old_time = settings.getString("modify_time", "");
			String new_time = Utils.getNowTime2();
			if (old_time.equals(new_time)) // 同一天
				bResult = true;
			else { // 不同的话, 初始化各值
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("modify_time", new_time);
				editor.putInt("shark_count", value);
				editor.putInt("circle_count", value);
				editor.commit();
			}

			if (G.DEBUG) {
				System.out.println("old_time: " + old_time);
				System.out.println("new_time: " + new_time);
			}

			return bResult;
		}

	}

	public static int getSharkCount(Activity activity, int default_vaule) {

		updateTimeAndCount(activity, default_vaule);

		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		{
			//
			int v = settings.getInt("shark_count", -1);
			if (v == -1)
				return default_vaule;

			return v;
		}

	}

	public static int getCircleCount(Activity activity, int default_vaule) {

		updateTimeAndCount(activity, default_vaule);

		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		{
			//
			int v = settings.getInt("circle_count", -1);
			if (v == -1)
				return default_vaule;

			return v;
		}

	}

	public static int getCircleCount_Dec(Activity activity, int value) {

		updateTimeAndCount(activity, value);

		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		// if( settings.getInt( "shark_count", -1) == -1 ){
		// return value;
		// }
		// else
		{
			//
			int v = settings.getInt("circle_count", value);
			SharedPreferences.Editor editor = settings.edit();
			{
				if (--v < 0)// 减少一次
					v = 0;

				editor.putInt("circle_count", v);
			}
			editor.commit();

			return v;
		}

	}

	// "shark_count"
	public static int getSharkCount_Dec(Activity activity, int value) {

		updateTimeAndCount(activity, value);

		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		// if( settings.getInt( "shark_count", -1) == -1 ){
		// return value;
		// }
		// else
		{
			//
			int v = settings.getInt("shark_count", value);
			SharedPreferences.Editor editor = settings.edit();
			{
				if (--v < 0)// 减少一次
					v = 0;

				editor.putInt("shark_count", v);
			}
			editor.commit();

			return v;
		}

	}

	/*
	 * public static void saveUserName(Activity activity, String userName,
	 * boolean isRemember) { SharedPreferences settings =
	 * activity.getSharedPreferences("userinfo", 0); SharedPreferences.Editor
	 * editor = settings.edit(); editor.putBoolean("isRemember", isRemember); if
	 * (isRemember) { editor.putString("userName", userName); } else {
	 * editor.putString("userName", ""); } editor.commit(); }
	 * 
	 * 
	 * public static void saveUserPassword(Activity activity, String password,
	 * boolean isRemember) { SharedPreferences settings =
	 * activity.getSharedPreferences("userinfo", 0); SharedPreferences.Editor
	 * editor = settings.edit(); editor.putBoolean("isRemember", isRemember); if
	 * (isRemember) { editor.putString("password", password); } else {
	 * editor.putString("password", ""); } editor.commit(); }
	 */

	/**
	 * 隐藏键盘
	 * 
	 * @param activity
	 */
	public static void hideKeybord(Activity activity) {
		try {
			((InputMethodManager) activity
					.getSystemService(activity.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(activity.getCurrentFocus()
							.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
			
		} catch (Exception e) {

		}

	}

	public static void showKeybord(Activity activity) {
		try {
			((InputMethodManager) activity
					.getSystemService(activity.INPUT_METHOD_SERVICE))
					.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

		} catch (Exception e) {

		}

	}


	public static boolean networkIsAvailable(Context context) {
		NetworkInfo info = ((ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();
		return (null != info && info.isAvailable());
	}

	public static final int NETTYPE_NOWIFI = 0;
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;

	/**
	 * 检测网络是否可用
	 * 
	 * @return
	 */
	public static boolean isNetworkConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}

	/**
	 * 获取当前网络类型
	 * 
	 * @return 0：没有网络 1：WIFI网络 2：WAP网络 3：NET网络
	 */
	public static int getNetworkType(Context context) {
		int netType = 0;
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			extraInfo = extraInfo.trim();
			if (extraInfo.length() != 0) {
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}

	// ////////////////////////////////////////////////////////////////////////

	/**
	 * 把数据源HashMap转换成json
	 * 
	 * @param map
	 */
	public static String hashMapToJson(HashMap map) {
		String string = "{";
		for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
			Entry e = (Entry) it.next();
			string += "'" + e.getKey() + "':";
			string += "'" + e.getValue() + "',";
		}
		string = string.substring(0, string.lastIndexOf(","));
		string += "}";
		return string;
	}

	/**
	 * 将整形转换成2100-10-10形式
	 * 
	 * @param token
	 * @return
	 */
	public static String getTime(String token) {
		token += "000";
		long time_long = Long.parseLong(token);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date(time_long));
	}

	/*
	 * 给出提示
	 */
	public static void NoticeNew(Activity activity, int length) {

		if ( G.DEBUG == false )
			return;

		if (length > 0) {

			String str = String.valueOf(length);
			Toast.makeText(activity, "已增加更新: " + str, Toast.LENGTH_SHORT)
					.show();

		} else {

			Toast.makeText(activity, "无新的内容~", Toast.LENGTH_SHORT).show();

		}

	}
	
	

	public static void showToastShort(Context context, int rid) {
		String message = context.getResources().getString(rid);
		showToastShort(context, message);
	}
	
	public static void showToastLong(Context context, int rid) {
		String message = context.getResources().getString(rid);
		showToastLong(context, message);
	}
	

	public static void showToastShort(Context context, String messsage) {
		/* 部分机器显示不完全
		LayoutInflater inflater=LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.layout_toast_normal, null);
		TextView tv_title = (TextView)view.findViewById(R.id.tv_title);
		tv_title.setText(messsage);

		Toast toast = new Toast(context);
		toast.setGravity(Gravity.BOTTOM, 0, dip2px(context, 50));
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(view);
		toast.show();
		*/

		Toast.makeText(context.getApplicationContext(), messsage, Toast.LENGTH_SHORT).show();


	}

	public static void showToastLong(Context context, String message) {

		/*
		LayoutInflater inflater=LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.layout_toast_normal, null);
		TextView tv_title = (TextView)view.findViewById(R.id.tv_title);
		tv_title.setText(messsage);

		Toast toast = new Toast(context);
		toast.setGravity(Gravity.BOTTOM, 0, dip2px(context, 50));
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(view);
		toast.show();
		*/

		Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_LONG).show();

	}

	public static void MessageBox(Activity activity, String text) {
		new AlertDialog.Builder(activity).setTitle("温馨提示").setMessage(text)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						dialog.dismiss();

					}
				})
				// .setNegativeButton("取消", new
				// DialogInterface.OnClickListener() {
				//
				// @Override
				// public void onClick(DialogInterface dialog, int which) {
				// // TODO Auto-generated method stub
				//
				// }
				// })
				.create().show();

	}
	
	
	///////////////////////////////////////////////////////////////////////

	/**
	 * 将本地图片转化为字符串，
	 * 
	 */
	public static String Image_ToBase64(String path) {

		if (mImage == null)
			mImage = new Utils_Image();

		return mImage.oom(path);
	}
	
	/**
	 * 将本地图片转化为字符串
	 */
	public static String Image_ToBase64_2(String path){
		if (mImage == null)
			mImage = new Utils_Image();

		return mImage.oom_2(path);
	}
	
	
	public static String Image_UrlToFile(String url) {

		if (mImage == null)
			mImage = new Utils_Image();

		return mImage.UrlPicSaveToDisk(url);
	}
	

	private static Utils_Image mImage;

	// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	private static ProgressDialog progress = null;

	/**
	 * 显示加载对话框
	 * 
	 * @param messsage
	 *            内容
	 */
	static public void showLoadingDialog(Context activity, String messsage) {

		if ((progress != null) && progress.isShowing()) {
			return;
		}
		progress = new ProgressDialog(activity);
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setMessage(messsage);
		progress.show();

	}

	//
	static public void showLoadingDialog(Context context, int messsage_id, boolean bCanCancel) {

		if ((progress != null) && progress.isShowing()) {
			return;
		}
		progress = new ProgressDialog(context);
		progress.setCanceledOnTouchOutside(bCanCancel);
		progress.setCancelable(bCanCancel);
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setMessage(context.getResources().getString(messsage_id));
		progress.show();

	}

	//
	static public void showLoadingDialog(Context context, String messsage, boolean bCanCancel) {

		if ((progress != null) && progress.isShowing()) {
			return;
		}
		progress = new ProgressDialog(context);
		progress.setCanceledOnTouchOutside(bCanCancel);
		progress.setCancelable(bCanCancel); 
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setMessage(messsage);
		progress.show();

	}
	
	

	static public void showLoadingDialog(Context activity, int messsage_id) {

		if ((progress != null) && progress.isShowing()) {
			return;
		}
		progress = new ProgressDialog(activity);
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setMessage( activity.getResources().getString(messsage_id) );
		progress.show();

	}
	
	

	/**
	 * 隐藏加载对话框
	 */
	static public void dismissLoadingDialog() {
		if (progress != null) {
			progress.dismiss();
			progress = null;
		}
	}

	static public void phone_call(Activity activity, String num) {

		Intent i = new Intent("android.intent.action.CALL", Uri.parse("tel:"
				+ num));
		activity.startActivity(i);

	}

	/*
	 * static public void showNotification(Activity activity,long cancelTime,
	 * String text) { try { Context app = activity.getApplicationContext();
	 * NotificationManager nm = (NotificationManager) app
	 * .getSystemService(Context.NOTIFICATION_SERVICE); final int id =
	 * Integer.MAX_VALUE / 13 + 1; nm.cancel(id);
	 * 
	 * long when = System.currentTimeMillis(); Notification notification = new
	 * Notification(notifyIcon, text, when); PendingIntent pi =
	 * PendingIntent.getActivity(app, 0, new Intent(), 0);
	 * notification.setLatestEventInfo(app, notifyTitle, text, pi);
	 * notification.flags = Notification.FLAG_AUTO_CANCEL; nm.notify(id,
	 * notification);
	 * 
	 * if (cancelTime > 0) {
	 * 
	 * 
	 * Message msg = new Message(); msg.what = MSG_CANCEL_NOTIFY; msg.obj = nm;
	 * msg.arg1 = id; UIHandler.sendMessageDelayed(msg, cancelTime, this);
	 * 
	 * } } catch (Exception e) { e.printStackTrace(); } }
	 */



	/**
	 * 判断密码是否有效
	 * 
	 * @param context
	 * @param password
	 * @return
	 */
	public static boolean vaildPassword(Context context, String password) { //

		boolean b = true;
		/*
		 * if( password.length() > 32){ // 限制长度 Utils1.showToastShort(context,
		 * "密码过长~"); b = false; }
		 */
		// 对java的正则无力... 判断是否有空格, 判断是否空字符串
		if (password == null || password.length() == 0)
			b = false;

		if (password.length() < 6 || password.length() > 32) {
			Utils.showToastShort(context, "密码长度范围为6-32个字符~");
			b = false;
		}

		// java的正则糟糕透了.
		Pattern p = Pattern.compile("[0-9a-zA-Z]*"); // 非[6,32]..
														// http://www.java3z.com/cwbwebhome/article/article8/Regex/Java.Regex.Tutorial.html
		Matcher m = p.matcher(password); //
		if (!m.matches())
			b = false;

		if (b == false) {
			// Utils1.showToastShort(context, "无效密码~"); // "请输入有效密码~"
			System.out.println("无效密码: " + password);
		}

		return b;

	}

	/**
	 * 简化代码而已
	 */
	public static void json_erro(Context context, JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		System.out.println("JSONException" + e.toString());
		Toast.makeText(context, "数据解析错误", Toast.LENGTH_SHORT).show();
	}

	public static boolean isEnglishWord(String str) { // digirun
		Pattern pattern = Pattern.compile("[a-zA-Z ]+");
		Matcher is = pattern.matcher(str);
		if (!is.matches()) {
			return false;
		}

		return true;
	}

	public static boolean isEnglish(CharSequence s) {

		boolean b = true;

		Pattern p = Pattern.compile("[a-zA-Z]*"); // 非[6,32].. s="abc" [a-zA-Z]
													// 为啥mathces()不上..
													// 不应该是匹配上a,b,c吗;
		Matcher m = p.matcher(s); //
		if (!m.matches())
			b = false;

		if (b == false) {
		}

		return b;

	}

	public static boolean isEmpty(String s) {
		if (s.trim().length() == 0)
			return true;
		else
			return false;
	}

	/*
	 * 
	 * class cClampLength { int change_length =0; int length =10;
	 * 
	 * public cClampLength() { // TODO Auto-generated constructor stub }
	 * 
	 * };
	 * 
	 * 
	 * private static cClampLength clamp; public static boolean
	 * clamp_length(String s){
	 * 
	 * if(clamp == null) return new cClampLength(); else return clamp; }
	 */

	/**
	 * @Description: TODO(判断sdcard是否可用)
	 * @author zhongyou.chen
	 * @date 2013-6-20
	 * @return
	 */
	public static boolean isSDCardAvailable() {
		if (Environment.getExternalStorageState().equals("mounted")) {
			return true;
		}
		return false;
	}

	/**
	 * @Description: TODO(判断网络是否可用)
	 * @author zhongyou.chen
	 * @date 2013-6-20
	 * @return
	 */
	public static boolean isNetworkAvailable(Context appContext) {
		Context context = appContext.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService("connectivity");
		if (connectivity == null) {
			return false;
		}
		NetworkInfo[] info = connectivity.getAllNetworkInfo();
		if (info != null) {
			for (int i = 0; i < info.length; i++) {
				if (info[i].isConnected()) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * @Description: TODO(获取当前时间)
	 * @author zhongyou.chen
	 * @date 2013-6-20
	 * @return
	 */
	public static String getNowTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		return format.format(Calendar.getInstance().getTime());
	}

	public static String getNowTime1() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(Calendar.getInstance().getTime());
	}

	public static String getNowTime2() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		return format.format(Calendar.getInstance().getTime());
	}
	
	public static String getNowTime3(String f) {
		SimpleDateFormat format = new SimpleDateFormat(f);
		return format.format(Calendar.getInstance().getTime());
	}



	public static int getStatusHeight(Activity activity) { // 可以使用Build判断版本;

		// 不支持某些版本.. android2.3.5
		int StatusHeight = activity.getWindow()
				.findViewById(Window.ID_ANDROID_CONTENT).getTop();

		if (StatusHeight == 0) {
			// 38像素 http://www.2cto.com/kf/201205/130561.html
			Class<?> c = null;
			Object obj = null;
			java.lang.reflect.Field field = null;
			int x = 0, sbar = 0;
			try {
				c = Class.forName("com.android.internal.R$dimen");
				obj = c.newInstance();
				field = c.getField("status_bar_height");
				x = Integer.parseInt(field.get(obj).toString());
				sbar = activity.getResources().getDimensionPixelSize(x);
			} catch (Exception e1) {
				Utils_Log.e("", "get status bar height fail");
				e1.printStackTrace();
			}

			StatusHeight = sbar;
		}

		return StatusHeight;

	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		// 宽和高都大于实际需要
		if (height > reqHeight || width > reqWidth) {
			if (width > height) { // 比较图片长宽,用最大的算比例...(int)Math.floor(a + 0.5f);
									// floor:函数返回不大于参数的最大整数
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}

	public static Bitmap decodeFile(String path, int REQUIRED_SIZE_x,
			int REQUIRED_SIZE_y) {
		try {
			// decode image size
			File file = new File(path);
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(file), null, o);

			// Find the correct scale value. It should be the power of 2.
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 <= REQUIRED_SIZE_x
						|| height_tmp / 2 <= REQUIRED_SIZE_y)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			o2.inPreferredConfig = Bitmap.Config.RGB_565;
			o2.inPurgeable = true;
			o2.inInputShareable = true;
			return BitmapFactory.decodeStream(new FileInputStream(path), null,
					o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	// http://bUtils_Log.csdn.net/sevensundark/article/details/7616450
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static boolean isAppOnForeground(Context context, String packageName) {
		// Returns a list of application processes that are running on the
		// device

		ActivityManager activityManager = (ActivityManager) context
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);

		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}

	public static boolean isAppOnBackground(Context context, String packageName) {
		// Returns a list of application processes that are running on the
		// device

		ActivityManager activityManager = (ActivityManager) context
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);

		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
				return true;
			}
		}

		return false;
	}

	static public void WaitMs(int delay) {
		try {
			Thread.sleep(delay);
		} catch (InterruptedException e) {
		}

	}

	// error
	public static boolean isContainNum(String str) {
		Pattern pattern = Pattern.compile("[0-9]+");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public static void do_hardwork() {
		try {
			Socket s = new Socket("11.11.11.11", 11);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
	}

	/**
	 * 发送App异常崩溃报告
	 * 
	 * @param cont
	 * @param crashReport
	 */
	public static void sendAppCrashReport(final Context cont, final String title,
			final String crashReport) {

		// 该方法将调用发送邮件程序
		Intent i = new Intent(Intent.ACTION_SEND);
		// i.setType("text/plain"); //模拟器
		i.setType("message/rfc822"); // 真机
		i.putExtra(Intent.EXTRA_EMAIL, new String[] { "1821423731@qq.com" }); // robot_001
		i.putExtra(Intent.EXTRA_SUBJECT, title);
		i.putExtra(Intent.EXTRA_TEXT, crashReport);
		cont.startActivity(Intent.createChooser(i, "发送错误报告"));
		// 退出

		System.exit(0);
		// ActivityManager.getInstance().exit();

	}

	// 20140221

	// 20140411
	public static String readAsset(String samulation, Context context) {
		AssetManager am = null;
		am = context.getAssets(); // 用来访问assets文件夹的管理器
		try {
			InputStream is = am.open(samulation); // 打开assets文件夹下的home.json文件
			int length = is.available();
			byte[] buffer = new byte[length];
			is.read(buffer);
			String res = new String(buffer);
			String jsonString = res.substring(res.indexOf("{"));
			return jsonString;
		} catch (IOException e) {
			e.printStackTrace();
			Utils_Log.e("error", e.toString());
			return "";
		}
	}

	// 20140414

	/**
	 * 
	 * @param context
	 * @param dir_name
	 * @return
	 */
	public static File getPath(Context context, String dir_name) {

		// 创建数据库目录
		//
		File sdCardpath = Environment.getExternalStorageDirectory();
		File dbPath = new File(sdCardpath, context.getPackageName());
		String str_dir = dbPath.getPath();
		File dir = new File(str_dir, dir_name); // /mnt/sdcard/***/dir_name
		if (!dir.exists())
			dir.mkdirs();

		return new File(dir, "pic.tmp");

	}

	// 20140417
	/**
	 * 如果isShowUserName,在isRemember为false的清空下,将能显示账号;
	 * 
	 * @param activity
	 * @param userName
	 * @param password
	 * @param isRemember
	 * @param isShowUserName
	 */
	public static void saveUserNameAndPassword(Activity activity,
			String userName, String password, boolean isRemember,
			boolean isShowUserName) {
		SharedPreferences settings = activity.getSharedPreferences("userinfo",
				0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("isRemember", isRemember);
		if (isRemember) {
			editor.putString("userName", userName);
			editor.putString("password", password);
		} else {
			editor.putString("userName", "");
			editor.putString("password", "");
		}

		if (isShowUserName) {
			editor.putString("userName", userName);
		}

		editor.commit();
	}

	public static String[] getUserNameAndPassword(Context context) {

		String[] t = new String[2];

		SharedPreferences settings = context
				.getSharedPreferences("userinfo", 0);
		t[0] = settings.getString("userName", "");
		t[1] = settings.getString("password", "");

		return t;

	}

	static Random random;

	// /
	public static float getRandom() {

		if (random == null)
			random = new Random(System.currentTimeMillis());

		return random.nextFloat();

	}

	public static void ToastUI(final Activity activity, final String msg) {

		activity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				showToastShort(activity, msg);
			}
		});

	}

	public static String Bytes2HexString(byte[] paramArrayOfByte) {
		String str1 = "";
		for (int i = 0;; ++i) {
			if (i >= paramArrayOfByte.length)
				return str1;
			String str2 = Integer.toHexString(0xFF & paramArrayOfByte[i]);
			if (str2.length() == 1)
				str2 = '0' + str2;
			str1 = str1 + str2.toUpperCase() + " ";
		}
	}

	private static byte charToByte(char paramChar) {
		return (byte) "0123456789ABCDEF".indexOf(paramChar);
	}

	public static String getTime_YYYYMMDD(String token) {
		token += "000";
		long time_long = Long.parseLong(token);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date(time_long));
	}

	public static String getTime_YYYYMMddHHmmss(long token){
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1=new Date(token);
		String t1=format.format(d1);
		return t1;
	}


	public static void Toast(final Activity activity, final String msg) {
		activity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Utils.showToastShort(activity, msg);
			}
		});

	}

	// http://kewell2004.iteye.com/blog/1545783
	private static long lastClickTime;

	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		lastClickTime = time;
		if (0 < timeD && timeD < 800) {
			return true;
		}
		return false;
	}

	/*
	 * 从网上找了快速点击的处理代码; public static class Time { private static Time mTime;
	 * private static long mExitTime;
	 * 
	 * private Time(){ mExitTime = System.currentTimeMillis(); }
	 * 
	 * public static Time getInstance(){ if(mTime == null) mTime = new Time();
	 * 
	 * return mTime; }
	 * 
	 * public boolean is_fast_click(){
	 * 
	 * boolean b = false;
	 * 
	 * if (System.currentTimeMillis() - mExitTime > 1000) { mExitTime =
	 * System.currentTimeMillis(); b = false; } else { b = true; }
	 * 
	 * if(G.DEBUG) System.out.println("is_fast_click: "+b);
	 * 
	 * 
	 * return b;
	 * 
	 * }
	 * 
	 * };
	 */

	public static boolean isPointInView(View view, Point point) {

		Rect r = new Rect();
		view.getLocalVisibleRect(r);

		int[] location = new int[2];
		view.getLocationOnScreen(location);

		if (G.DEBUG)
			System.out.println("getLocationOnScreen: " + location[0] + " "
					+ location[1]);

		r.offset(location[0], location[1]);

		if (G.DEBUG) {
			System.out.println("最终矩形数据: " + r.toString());
			System.out.println("最终点数据: " + point.toString());
		}

		if (r.contains(point.x, point.y)) {
			if (G.DEBUG)  
				System.out.println("在目标区域.");

			return true;
		}

		return false;

	}

	// /////////////2014/05/17

	public static String DecString(String str) {
		Integer i = Integer.valueOf(str);
		return "" + (--i); // 如果这样写""+(i--); i值仍然是减之前的值

	}

	public static String AccString(String str) {
		Integer i = Integer.valueOf(str);
		return "" + (++i);
	}

	public static String getDateYear() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(new java.util.Date());
		String[] bt = date.split("-");
		String s = "";
		for (int i = 0; i < bt.length; i++) {
			s += bt[i];
		}
		return bt.toString();
	}

	/**
	 * 判断缓存是否存在
	 * 
	 * @param cachefile
	 * @return
	 */
	private boolean isExistDataCache(Activity activity, String cachefile) {
		boolean exist = false;
		File data = activity.getFileStreamPath(cachefile);
		if (data.exists())
			exist = true;
		return exist;
	}

	/**
	 * 保存对象
	 * 
	 * @param ser
	 * @param file
	 * @throws IOException
	 */
	public boolean saveObject(Activity activity, Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = activity.openFileOutput(file, 0);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				oos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 读取对象
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public Serializable readObject(Activity activity, String file) {
		if (!isExistDataCache(activity, file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = activity.openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable) ois.readObject();
		} catch (FileNotFoundException e) {
		} catch (Exception e) {
			e.printStackTrace();
			// 反序列化失败 - 删除缓存文件
			if (e instanceof InvalidClassException) {
				File data = activity.getFileStreamPath(file);
				data.delete();
			}
		} finally {
			try {
				ois.close();
			} catch (Exception e) {
			}
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

	public static boolean isConnectInternet(Context context) {

		int type = getNetworkType(context);
		if (type == NETTYPE_NOWIFI)
			return false;
		else
			return true;

	}

	public static String JSONTokener(String in) {
		// consume an optional byte order mark (BOM) if it exists
		if (in != null && in.startsWith("\ufeff")) {
			in = in.substring(1);
		}
		return in;
	}

	//
	public static String getIPAddress() {

		// /*
		String str_url = "http://iframe.ip138.com/ic.asp";

		// Utils1 m = new Utils1();
		// m.start_GET();

		/*
		 * String jsonString = ""; InputStream inputStream = null; try {
		 * StringBuilder params = new StringBuilder("");
		 * 
		 * BasicHttpParams httpParams = new BasicHttpParams();
		 * HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
		 * HttpConnectionParams.setSoTimeout(httpParams, 20000); // HttpClient
		 * client = new DefaultHttpClient(httpParams);
		 * 
		 * HttpGet request = new HttpGet(url + params); Utils_Log.e(TAG,
		 * "------------------------------------------------"); Utils_Log.e(TAG,
		 * "URL=" + url + params); HttpResponse response =
		 * client.execute(request); HttpEntity httpEntity =
		 * response.getEntity(); int StatusCode =
		 * response.getStatusLine().getStatusCode(); Utils_Log.e(TAG, "StatusCode=" +
		 * StatusCode );
		 * 
		 * if ( StatusCode == 200){ inputStream = httpEntity.getContent();
		 * BufferedReader reader = new BufferedReader( new
		 * InputStreamReader(inputStream)); String result = ""; String line =
		 * ""; while ((line = reader.readLine()) != null) { result = result +
		 * line; } System.out.println("====================="+result);
		 * inputStream.close(); jsonString = result; }
		 * 
		 * return jsonString;
		 * 
		 * } catch (Exception e) { e.printStackTrace(); Utils_Log.e(TAG,
		 * e.toString()); return ""; }
		 */
		// */

		// /* OK
		try {
			URL url = new URL(str_url);
			URLConnection conn = url.openConnection();
			conn.setRequestProperty("Charset", "gb2312");
			InputStream inputStream = conn.getInputStream();
			byte[] bytes = new byte[4096];
			int length = 0;
			byte[] data = new byte[0];
			byte[] tmpdata = null;
			while (((length = inputStream.read(bytes, 0, 4096))) > 0) {
				tmpdata = new byte[length + data.length];
				System.arraycopy(data, 0, tmpdata, 0, data.length);
				System.arraycopy(bytes, 0, tmpdata, data.length, length);
				data = tmpdata;
			}

			inputStream.close();

			String str = new String(bytes, "gb2312");
			System.out.println("  " + str);
			int start = str.indexOf("[");
			int end = str.indexOf("]");
			str = str.substring(start + 1, end - 1);
			System.out.println("ip: " + str);
			return str;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// */

		return "";

	}

	public static boolean isVaildUserName(String str) {
		boolean b = true;

		// /*
		char[] ch = str.toCharArray(); // 把字符型变量转换成字符串。
		for (int i = 0; i < ch.length; i++) {
			if (('a' <= ch[i] && ch[i] <= 'z')
					|| ('A' <= ch[i] && ch[i] <= 'Z')
					|| ('0' <= ch[i] && ch[i] <= '9')
					|| (0x4e00 <= ch[i] && ch[i] <= 0x9fa5) // 是否中文
			) {

			} else {
				b = false;
				break;
			}

		}

		return b;
	}
	
	// http://wister.iteye.com/blog/334562
	public static boolean isChineseWord(String str) {
		boolean b = true;

		String[][] temp = new String[str.length()][];

		// 汉语拼音格式输出类
//		HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();

		// /*
		char[] ch = str.toCharArray(); // 把字符型变量转换成字符串。
		for (int i = 0; i < ch.length; i++) {
			if (String.valueOf(ch[i]).matches("[\\u4E00-\\u9FA5]+") // 是否中文
																	// 可以过滤掉中文符号
			) {

				/*
				 * 担心过滤不掉中文字符 try{ System.out.println("pinyin check: "+ch[i]);
				 * temp[i] = PinyinHelper.toHanyuPinyinStringArray(ch[i],
				 * hanYuPinOutputFormat);
				 * }catch(BadHanyuPinyinOutputFormatCombination e) {
				 * e.printStackTrace();
				 * 
				 * b = false; break; }
				 */

			} else {
				b = false;
				break;
			}

		}

		return b;
	}
	
	
	
    /**
     * 提供精确的小数位四舍五入处理。
     * 
     * @param v
     *            需要四舍五入的数字
     * @param scale
     *            小数点后保留几位
     * @return 四舍五入后的结果
     */

    public static double round(Double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }

        BigDecimal b = null == v ? new BigDecimal("0.0") : new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    
	
    
    /**
	 * 调用系统相机
	 * 
	 * 
	 */
	public static File takePhoto(Activity activity, String SavePath) {

		// 判断SDCard是否存在
		boolean sdcardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) {
			/*
			 * SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			 * Date dt = new Date(); //
			 * 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型 String name =
			 * sdf.format(dt);
			 */
			File file = new File(SavePath, "temp_camera_pic.jpg");
			if (G.DEBUG)
				System.out.println(file);
			File pare = new File(file.getParent());
			if (!pare.exists()) {
				pare.mkdirs();
			}
			Intent takePictureFromCameraIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);
			takePictureFromCameraIntent.putExtra(
					android.provider.MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(file));
			activity.startActivityForResult(takePictureFromCameraIntent, 1002);

			return file;

		} else {

			String title = "温馨提示", messsage = "请检测是否安装SDCard", btnName = "确认";
			new AlertDialog.Builder(activity)
					.setTitle(title)
					.setMessage(messsage)
					.setPositiveButton(btnName,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							}).create().show();

		}

		return null;

	}
	
//////////////////////////m framework/////////////////////////////////////
	
	  public static boolean isNullOrEmpty(String str)
	  {
	    return (str == null) || 
	      (str.trim().length() <= 0) || 
	      ("null".equals(str.trim().toLowerCase(Locale.getDefault())));
	  }
	
//////////////////////////m framework/////////////////////////////////////	
	

	  
	  public static void make_me_crash(){
		  int i = 1/0;
	  }
	
	  
	  
		// http://www.360doc.com/content/12/1113/15/9462341_247605373.shtml
	  // 得到手机运营商
		public static String getMobileOperator(Context context){  
			TelephonyManager mTm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);  
			
	        String imei = mTm.getDeviceId();  // 手机串号
	        String imsi = mTm.getSubscriberId();  // SIM卡序列号    有可能得不到
	        String mtype = android.os.Build.MODEL; // 手机型号  
	        
	        if(imsi == null )
	        	return "";
	        
	        System.out.println("SIM卡序列号: "+imsi);
	        
	        String str ="";
	        if (imsi.startsWith("46000"))
	         str = "中国移动";  
	        else if (imsi.startsWith("46002"))
	         str = "中国移动"; 
	        else if (imsi.startsWith("46001"))
	          str = "中国联通";
	        else if (imsi.startsWith("46003"))
	          str = "中国电信";
	        else
	        	;
	        
	        return str;
	        
		}
		
			
		public static String getMobile_imei( Context context) {	  
	        TelephonyManager mTm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);  

	        String imei = mTm.getDeviceId();  // 手机串号
	        String imsi = mTm.getSubscriberId();  // SIM卡序列号    有可能得不到
	        String mtype = android.os.Build.MODEL; // 手机型号  
	        String numer = mTm.getLine1Number(); // 手机号码，有的可得，有的不可得

	        /* 需要ACCESS_**_LOCATION声明。还有是否在同一个进程的麻烦；
	        int Type =mTm.getNetworkType(); // 0
	        List<NeighboringCellInfo> infos =mTm.getNeighboringCellInfo(); //seals 得不到
	        for(NeighboringCellInfo info:infos){
	            //获取邻居小区号
	            int cid=info.getCid();
	            //获取邻居小区LAC，LAC: 位置区域码。为了确定移动台的位置，每个GSM/PLMN的覆盖区都被划分成许多位置区，LAC则用于标识不同的位置区。
	            info.getLac();
	            info.getNetworkType();
	            info.getPsc();
	            //获取邻居小区信号强度  
	            info.getRssi();
	        }
	        */
	        
	        int PhoneType =mTm.getPhoneType(); // PHONE_TYPE_GSM 1
	        
	        System.out.println("imei: "+imei);
	        
	        String SerialNum = mTm.getSimSerialNumber();
	        
	     // String OperatorName = mTm.getSimOperatorName();   
	    //    String SerialNum =android.os.Build.SERIAL;
	 //       String SDK_Version = android.os.Build.VERSION.SDK; // API编号  //OK
	        String OS_Version = android.os.Build.VERSION.RELEASE; // os编号
	        
	   /*     
	       String SerialNum = mTm.getSimSerialNumber();
	       String opera = mTm.getSimOperator();
	     */  
	        
	        return imei;
	        
	    }

		public static String readFile(String path) {
			try {
				
				FileInputStream is = new FileInputStream(path);
				int length = is.available();
				byte[] buffer = new byte[length];
				is.read(buffer);
				String res = new String(buffer);
				return res;
			} catch (IOException e) {
				e.printStackTrace();
				Utils_Log.e("error", e.toString());
				return "";
			}
		}

		public static byte[] readFile2Bytes(String path){
			try {

				FileInputStream is = new FileInputStream(path);
				int length = is.available();
				byte[] buffer = new byte[length];
				is.read(buffer);
				return buffer;
			} catch (IOException e) {
				e.printStackTrace();
				Utils_Log.e("error", e.toString());
			}

			return new byte[0];

		}




	
		
		/**
		 * 判断座机号码格式是否正确
		 * 
		 * @param mobiles
		 * @return
		 */
		public static boolean isTelNO(String Tel) {
			Pattern p = Pattern
					.compile("^(0[0-9]{2,3}\\-)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?$");
			Matcher m = p.matcher(Tel);
			return m.matches();
		}
		
		
		/*
		public static void changeSize(Activity activity){

			DisplayMetrics metrics = new DisplayMetrics();
			activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		     int mDensity = metrics.densityDpi;
		     System.out.println("DPI: "+mDensity);
		    if (mDensity >= 120 && mDensity < 240) {  // 120dpi 160dpi 240dpi 320dpi   
		    	webview.setInitialScale(35);
	       }else if (mDensity >= 240 && mDensity < 320) {
	    	   webview.setInitialScale(70);
	       }
	       else if(mDensity >= 320){
	    	   webview.setInitialScale(100);
	       }
		     
		     
		}
		*/
		
		public static void ShowToastCustom(Context ctx, String content) {
			LayoutInflater inflater=LayoutInflater.from(ctx.getApplicationContext());
			View view = inflater.inflate(R.layout.layout_toast, null);
			TextView tv_title = (TextView)view.findViewById(R.id.tv_title);
			TextView tv_percentage = (TextView)view.findViewById(R.id.tv_percentage);

			tv_title.setText(content);
			
			  Toast toast = new Toast(ctx.getApplicationContext());
			  toast.setGravity(Gravity.CENTER, 0, 0);
			  toast.setDuration(Toast.LENGTH_LONG);
			  toast.setView(view);
			  toast.show();
		}
		
		
		public static int dpToPx(Resources res, int dp) {
			return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics());
		}
		
		
		
		public static String getIPAddress_fromtaobao(){
			
			String str_url ="http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
			String ip = "";
			
			try {
				URL url = new URL(str_url);
				URLConnection conn = url.openConnection();
				InputStream inputStream = conn.getInputStream();
				byte[] bytes = new byte[4096];
				byte[] data = new byte[0];	//存储结果
				byte[] tmpdata = null;
				int length = 0;
				while (((length = inputStream.read(bytes, 0, 4096))) > 0) {
					tmpdata = new byte[length + data.length];
					System.arraycopy(data, 0, tmpdata, 0, data.length);
					System.arraycopy(bytes, 0, tmpdata, data.length, length);
					data = tmpdata;
				}
				inputStream.close();

				JSONObject obj = new JSONObject( new String(data) );
				String code = obj.getString("code");
				if( code.equals("0") ){
					JSONObject obj_data = obj.getJSONObject("data");
					ip = obj_data.getString("ip");
					
				}
				
				
				
				
				Utils_Log.d(TAG, ip);
				
				
				
				 
				return ip;

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			
			return ip;
			
		}
		
		
		/**
		 * 说明：拨号由用户点击控制
		 * 
		 * @param phone
		 *            电话号码
		 */
		public static void dialPhone(Context ctx, String phone) {

			Utils_Log.i(TAG, "拨打电话：用户点击");
			Intent intent = new Intent(Intent.ACTION_DIAL);
			intent.setData(Uri.parse("tel:" + phone));
			ctx.startActivity(intent);
		}

		/**
		 * 说明：拨号由APP直接拨打控制
		 * 
		 * @param phone
		 *            电话号码
		 */
		public static void callPhone(Context ctx, String phone) {

			Utils_Log.i(TAG, "拨打电话：无需点击");
			Intent intent = new Intent(Intent.ACTION_CALL);
			intent.setData(Uri.parse("tel:" + phone));
			ctx.startActivity(intent);
		}

		/**
		 * 说明：跳转到系统网络设置页面
		 * 
		 * @param ctx
		 *            上下文
		 */
		public static void rediectToNetworkSetting(Context ctx) {

			Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
			ctx.startActivity(intent);

		}

		
		
		public static void TipsDialog(Activity activity, String msg, DialogInterface.OnClickListener listener_ok, DialogInterface.OnClickListener listener_cancel){
			new AlertDialog.Builder(activity).setTitle("温馨提示").setMessage(msg)
			.setPositiveButton("确认", listener_ok)
			.setNegativeButton("取消", listener_cancel).create().show();
		}
		
		
		public static void TipsDialog(Activity activity, String msg, DialogInterface.OnClickListener listener_ok){
			new AlertDialog.Builder(activity).setTitle("温馨提示").setMessage(msg)
			.setPositiveButton("确认", listener_ok)
			.create().show();
		}


	public static boolean isJSONObject(String str){
		boolean b = true;
		try {
			JSONObject obj = new JSONObject(str);
		} catch (JSONException e) {
			b = false;
		}

		return b;
	}

	public static boolean isJSONArray(String str){
		boolean b = true;
		try {
			JSONArray array = new JSONArray(str);
		} catch (JSONException e) {
			b = false;
		}

		return b;
	}


	public static boolean isJSONObjectHad(String json, String str){
		boolean b = true;
		try {
			JSONObject obj = new JSONObject(json);
			return obj.has(str);
		} catch (JSONException e) {
			b = false;
		}

		return b;
	}


	//http://www.cnblogs.com/rayray/archive/2013/08/01/3230131.html
	//判断当前设备是否是模拟器。如果返回TRUE，则当前是模拟器，不是返回FALSE
	public static boolean isEmulator(Context context){
		try{
			TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			String imei = tm.getDeviceId();
			if (imei != null && imei.equals("000000000000000")){
				return true;
			}
			return  (Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"));
		}catch (Exception ioe) {

		}
		return false;
	}


	static void trans_stream(OutputStream out, InputStream in) throws IOException {
		byte tmp[] = new byte[1024];
		int len = 0;
		while ((len = in.read(tmp, 0, 1024)) != -1) {
			out.write(tmp, 0, len);
		}

	}


	public static void CopyFileFromStream(File dest, InputStream src) throws IOException {
		FileOutputStream fos = null;
		try {

			fos = new FileOutputStream(mkdirFiles(dest.getAbsolutePath()));

			trans_stream(fos, src);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (src != null) {
				src.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}


	public static void CopyFile(File dest, File src) throws IOException {

		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {

			fis = new FileInputStream(src);
			fos = new FileOutputStream(mkdirFiles(dest.getAbsolutePath()));

			trans_stream(fos, fis);


		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}

	}

	/**
	 * 根据filePath创建相应的目录
	 *
	 * @param filePath 要创建的文件路经
	 * @return file        文件
	 * @throws IOException
	 */
	public static File mkdirFiles(String filePath) throws IOException {
		File file = new File(filePath);
		File parent = file.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
		boolean b = file.createNewFile();

		return file;
	}


	/**
	 * 获取单个文件的MD5值！

	 * @param file
	 * @return
	 */

	public static String getMd5ByFile(File file) {
		if (!file.isFile()) {
			return null;
		}
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);
	}

	public static String getMd5ByFile(InputStream in) {
		MessageDigest digest = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);
	}



}







